// pages/gatherHouse/com/com-loading/com-loading.js
import p from '../../../../utils/platform'
const computedBehavior = require('miniprogram-computed')


Component({
  behaviors: [computedBehavior],

  /**
   * 组件的属性列表
   */
  properties: {
    isOk: {
      type: Boolean,
      value: false
    },
  },

  options: {
    styleIsolation: 'apply-shared',
    addGlobalClass: true,
  },

  observers: {
    isOk() {
      if (this.data.isOk) {
        this.data.base = 3
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    base: 0,
    process: 0,
    timeOut: null,
    failingTimer: null, //加载超时后的定时器
  },

  computed: {
    processParse(data) {
      return Math.floor(data.process)
    }
  },

  
  lifetimes: {
    // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
    attached: function() {
      this.data.base = 0.3
      this.start()
    },
    moved: function() {},
    detached: function() {
      this.clear()
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    start() {
      if (this.data.timeOut) {
        clearInterval(this.data.timeOut)
        this.data.timeOut = null
      }
      this.data.timeOut = setInterval(this.addProcess.bind(this), 50)
    },
    addProcess() {
      this.setData({
        process: Math.min(this.data.process + this.data.base, 100)
      })

      if (this.data.process>=99 && !this.data.isOk) {
        this.clear()

        this.data.failingTimer = setTimeout(() => {
          this.triggerEvent("ontimeoutfn")
        }, 3000)

        return
      }

      if (this.data.process>=60 && !this.data.isOk) {
        this.data.base = 0.005
      }
      
      if (this.data.process >= 100) {
        this.accomplish()
      }
    },

    accomplish() {
      this.clear()

      setTimeout(() => {
        this.triggerEvent("onloadhousedone")
        p.showToast({
          title: "录房完成！",
          icon: "success",
        })
      }, 500)
    },

    clear() {
      if (this.data.timeOut) {
        clearInterval(this.data.timeOut)
        this.data.timeOut = null
      }

      if (this.data.failingTimer) {
        clearTimeout(this.data.failingTimer)
        this.data.failingTimer = null
      }
    },
  }
})
